Page({
  data: {
    formData: {
      name: '',
      phone: '',
      email: '',
      subject: '',
      message: '',
      urgency: 'normal'
    },
    urgencyOptions: [
      { value: 'low', label: '一般' },
      { value: 'normal', label: '普通' },
      { value: 'high', label: '紧急' },
      { value: 'urgent', label: '非常紧急' }
    ],
    submitting: false
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '在线留言'
    })
    
    // 尝试获取用户信息自动填充
    this.loadUserInfo()
  },

  // 加载用户信息
  async loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.setData({
          'formData.name': userInfo.nickName || '',
          'formData.phone': userInfo.phone || ''
        })
      }
    } catch (error) {
      console.log('获取用户信息失败:', error)
    }
  },

  // 输入框变化
  onInputChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 紧急程度选择
  onUrgencyChange(e) {
    const { value } = e.detail
    this.setData({
      'formData.urgency': this.data.urgencyOptions[value].value
    })
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      })
      return false
    }
    
    // 简单的手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/
    if (!phoneRegex.test(formData.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.subject.trim()) {
      wx.showToast({
        title: '请输入留言主题',
        icon: 'none'
      })
      return false
    }
    
    if (!formData.message.trim()) {
      wx.showToast({
        title: '请输入留言内容',
        icon: 'none'
      })
      return false
    }
    
    return true
  },

  // 提交留言
  async submitMessage() {
    if (!this.validateForm()) {
      return
    }
    
    if (this.data.submitting) {
      return
    }
    
    this.setData({ submitting: true })
    
    wx.showLoading({
      title: '提交中...'
    })
    
    try {
      // 调用云函数提交留言
      const result = await wx.cloud.callFunction({
        name: 'businessManager',
        data: {
          action: 'submitMessage',
          messageData: {
            ...this.data.formData,
            submitTime: new Date(),
            status: 'pending'
          }
        }
      })
      
      wx.hideLoading()
      
      if (result.result.success) {
        wx.showModal({
          title: '提交成功',
          content: '您的留言已提交成功，我们会在24小时内回复您。',
          showCancel: false,
          confirmText: '确定',
          success: () => {
            wx.navigateBack()
          }
        })
      } else {
        throw new Error(result.result.error || '提交失败')
      }
      
    } catch (error) {
      wx.hideLoading()
      console.error('提交留言失败:', error)
      
      wx.showModal({
        title: '提交失败',
        content: '留言提交失败，请稍后重试或联系客服。',
        showCancel: false,
        confirmText: '确定'
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  // 重置表单
  resetForm() {
    wx.showModal({
      title: '确认重置',
      content: '确定要清空所有内容吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            formData: {
              name: '',
              phone: '',
              email: '',
              subject: '',
              message: '',
              urgency: 'normal'
            }
          })
          wx.showToast({
            title: '已重置',
            icon: 'success'
          })
        }
      }
    })
  }
})
